package com.wisenet.controller.client.wxpubno;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;

import javax.net.ssl.HttpsURLConnection;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.alibaba.fastjson.JSONObject;
import com.wisenet.annotation.LoginValidate;
import com.wisenet.cache.SimpleCacheProvider;
import com.wisenet.common.PayConst;
import com.wisenet.common.WxConst;
import com.wisenet.controller.PlatformController;
import com.wisenet.entity.WeixinPubno;
import com.wisenet.pojo.jssdkpojo.Config;
import com.wisenet.pojo.menupojo.AccessToken;
import com.wisenet.service.wx.WechatUserService;
import com.wisenet.service.wxpubno.WeixinService;
import com.wisenet.util.PropertiesUtil;
import com.wisenet.util.TencentOssUtil;
import com.wisenet.wx.util.FileUtil;
import com.wisenet.wx.util.WeChatApiUtil;
import com.wisenet.wx.util.WeixinUtil;

/**
 * 微信公众平台接口控制类
 * @author fzh
 */
@Controller
@RequestMapping("/wx/open")
public class WeixinController extends PlatformController {
	@Autowired
	WeixinService weixinService;
	@Autowired
	WechatUserService userService;
	@Autowired
	private SimpleCacheProvider simpleCacheProvider;
	// 日志
	public static Logger logger = Logger.getLogger(WeixinController.class);

	/**
	 * 网页授权回调域名配置
	 * @param echostr
	 * @return
	 */
	@LoginValidate(value = false)
	@RequestMapping(value = "/MP_verify_{echostr}.txt")
	public @ResponseBody String returnConfigFile(@PathVariable("echostr") String echostr) {
		return echostr;
	}
	
	/**
	 * 网页跳转授权（前端访问路径：/wx/open/redirect?page=abyy&app=appid&scope=snsapi_base/userinfo）
	 * @param response
	 * @param request
	 * @throws IOException
	 */
	@LoginValidate(value = false)
	@RequestMapping(value = "/redirect", method = RequestMethod.GET)
	public void redirect2Oauth(HttpServletResponse response, HttpServletRequest request) throws IOException {
		response.setHeader("Content-Type", "text/plain; charset=UTF-8");
		PrintWriter print = null;
		
		// 获取小程序信息
		WeixinPubno pubno = simpleCacheProvider.get(request.getParameter("app"));
		if (pubno == null) {
			print = response.getWriter();
			print.write("APP不存在");
			print.close();
			return;
		}
		
		String URI = PropertiesUtil.getCurrentPropertiesValue("oauth2", "common.properties") + request.getQueryString();
		// 网页授权链接 /wx/open/oauth2?
		String redirectUrl = WeixinUtil.getOauth2Url(pubno.getAppid(), URI, request.getParameter("scope"));
		logger.info("redirectUrl = " + redirectUrl);
		response.sendRedirect(redirectUrl);
	}
	
	/**
	 * 网页授权回调
	 * @param response
	 * @param request
	 * @throws IOException
	 */
	@LoginValidate(value = false)
	@RequestMapping(value = "/oauth2", method = RequestMethod.GET)
	public void oauth2GetOpenid(HttpServletResponse response, HttpServletRequest request) throws IOException {
		response.setHeader("Content-Type", "text/plain; charset=UTF-8");
		
		PrintWriter print = null;
		
		// 获取小程序信息
		WeixinPubno pubno = simpleCacheProvider.get(request.getParameter("app"));
		if (pubno == null) {
			print = response.getWriter();
			print.write("APP不存在");
			print.close();
			return;
		}
		
		AccessToken accessToken = WeixinUtil.getAccessToken(pubno.getAppid(), pubno.getAppsecret(), request.getParameter("code"));
		if (accessToken == null) {
			print = response.getWriter();
			print.write("ACCESS_TOKEN不存在");
			print.close();
			return;
		}
		
		// 保存用户信息
		if (WxConst.OAUTH2_SCOPE_USERINFO.equals(request.getParameter("scope"))) {
			userService.saveUser(accessToken.getToken(), accessToken.getOpenid(), request.getParameter("remark"));
		}
		
		// 跳转链接 /wx/open/toPage?
		String redirectURI = PropertiesUtil.getCurrentPropertiesValue("redirectURI", "common.properties");
		redirectURI += request.getQueryString() + "&openid=" + accessToken.getOpenid();
		response.sendRedirect(redirectURI);
	}
	
	/**
	 * 保存图片，从微信服务器下载图片到本地
	 * @param mediaId
	 * @param app
	 * @return
	 */
	@LoginValidate(value = false)
	@RequestMapping(value = "/savePicture", method = RequestMethod.GET)
	public @ResponseBody JSONObject savePicture(String mediaId, String app) {
		JSONObject resultJson = getJsonResult(mediaId);
		if (!resultJson.getBooleanValue(SUCCESS)) {
			return resultJson;
		}
		// 获取公众号信息
		WeixinPubno pubno = simpleCacheProvider.get(app);
		if (pubno == null) {
			resultJson.put(SUCCESS, false);
			resultJson.put(MESSAGE, "APP不存在");
			return resultJson;
		}
		// 获取TOKEN
		String token = weixinService.getToken(pubno.getAppid(), pubno.getAppsecret());
		if (token == null) {
			resultJson.put(SUCCESS, false);
			resultJson.put(MESSAGE, "获取TOKEN失败");
			return resultJson;
		}
		
		// 获取微信临时素材并保存到服务器
		String requestUrl = String.format(WxConst.GET_MEDIA_URL, token, mediaId);
		logger.info("获取微信临时素材 requestUrl = " + requestUrl);
		try {
			// 获取小程序信息
			pubno = simpleCacheProvider.get(PayConst.MINI_APP_ID);
			if (pubno == null) {
				resultJson.put(SUCCESS, false);
				resultJson.put(MESSAGE, "APP不存在");
				return resultJson;
			}
			// 获取TOKEN
			token = weixinService.getToken(pubno.getAppid(), pubno.getAppsecret());
			if (token == null) {
				resultJson.put(SUCCESS, false);
				resultJson.put(MESSAGE, "获取TOKEN失败");
				return resultJson;
			}
			
			// 图片检测
			HttpsURLConnection httpUrlConn = FileUtil.getFile(requestUrl);
			resultJson = WeChatApiUtil.checkImage(httpUrlConn.getInputStream(), token);
			resultJson.put(SUCCESS, true);
			if (resultJson.getIntValue("errcode") != 0) {
				resultJson.put(SUCCESS, false);
				resultJson.put(MESSAGE, "图片有敏感内容");
				logger.info("图片检测：" + resultJson);
				return resultJson;
			}
			
			// 上传图片到腾讯云
			httpUrlConn = FileUtil.getFile(requestUrl);
			String key = "ocrweb/" + Math.abs(UUID.randomUUID().hashCode()) + ".jpg";
			TencentOssUtil tCloud = new TencentOssUtil();
			String picUrl = tCloud.uploadImage(key, httpUrlConn.getContentLength(), httpUrlConn.getInputStream());
			
			logger.info("显示图片链接 picUrl = " + picUrl);
			
			resultJson.put("picUrl", picUrl);
			
			httpUrlConn.disconnect();
		} catch (Exception ex) {
			resultJson.put(SUCCESS, false);
			resultJson.put(MESSAGE, "保存图片失败: " + ex.getMessage());
		}
		return resultJson;
	}
	
	/**
	 * 获取JssdkConfig
	 * @param url
	 * @param app
	 * @return
	 */
	@LoginValidate(value = false)
	@RequestMapping(value = "/getConfig", method = RequestMethod.GET)
	public @ResponseBody JSONObject getJssdkConfig(String url, String app) {
		JSONObject resultJson = getJsonResult(url, app);
		if (!resultJson.getBooleanValue(SUCCESS)) {
			return resultJson;
		}
		// 获取小程序信息
		WeixinPubno pubno = simpleCacheProvider.get(app);
		if (pubno == null) {
			resultJson.put(SUCCESS, false);
			resultJson.put(MESSAGE, "APP不存在");
			return resultJson;
		}
		// 获取TOKEN
		String token = weixinService.getToken(pubno.getAppid(), pubno.getAppsecret());
		if (token == null) {
			resultJson.put(SUCCESS, false);
			resultJson.put(MESSAGE, "获取TOKEN失败");
			return resultJson;
		}
		// 获取ticket
		String ticket = weixinService.getTicket(pubno.getAppid(), token);
		if (ticket == null) {
			resultJson.put(SUCCESS, false);
			resultJson.put(MESSAGE, "获取TICKET失败");
			return resultJson;
		}
		// 设置JssdkConfig
		Config config = WeixinUtil.setConfig(pubno.getAppid(), pubno.getAppsecret(), url, ticket);
		resultJson.put(RESULT, config);
		return resultJson;
	}
	
	/**
	 * 跳转页面
	 * @param page
	 * @return
	 */
	@LoginValidate(value = false)
	@RequestMapping(value = "/toPage", method = RequestMethod.GET)
	protected ModelAndView toPage(String page) {
		logger.info("page = " + page);
		ModelAndView mav = new ModelAndView(page);
		if (StringUtils.isBlank(page)) {
			mav.setView(new RedirectView("https://www.baidu.com"));
		} else if (page.contains("redirect")) {
			// https://mmnews.net.cn/photoFrame/wx/open/toPage?page=https://mp.weixin.qq.com/s/-0Oaa0qv8wz95-g9eUtNnQ%23redirect
			mav.setView(new RedirectView(page));
		}
		return mav;
	}
	
	
	/**
	 * 测试方法，用于微信接口菜单生成等
	 * @param jsondata
	 * @param app
	 * @param method
	 * @return
	 */
	@LoginValidate(value = false)
	@RequestMapping(value = "/test")
	public @ResponseBody JSONObject test(String jsondata, String app, String method) {
		JSONObject resultJson = getJsonResult(jsondata, app, method);
		if (!resultJson.getBooleanValue(SUCCESS)) {
			return resultJson;
		}
		// 获取小程序信息
		WeixinPubno pubno = simpleCacheProvider.get(app);
		if (pubno == null) {
			resultJson.put(SUCCESS, false);
			resultJson.put(RESULT,  ERROR);
			resultJson.put(MESSAGE, "APP不存在");
			return resultJson;
		}
		// 获取token
		String token = weixinService.getToken(pubno.getAppid(), pubno.getAppsecret());
		if (token == null) {
			resultJson.put(SUCCESS, false);
			resultJson.put(MESSAGE, "获取TOKEN失败");
			return resultJson;
		}
		
		resultJson.put("token", token);
		
		int result = -1;
		if ("menu".equals(method)) {
			// 创建个性化菜单
			result  = WeixinUtil.createConditionalMenu(jsondata, token);
		} else if ("add".equals(method)) {
			// 创建标签  {"tag":{"name":"标签"}}
			result = WeixinUtil.createTags(JSONObject.parseObject(jsondata), token);
		} else if ("edit".equals(method)) {
			// 编辑标签  {"tag":{"id":134,"name":"标签"}}
			result = WeixinUtil.updateTags(JSONObject.parseObject(jsondata), token);
		} else if ("del".equals(method)) {
			// 删除标签  {"tag":{"id":134}}
			result = WeixinUtil.deleteTags(JSONObject.parseObject(jsondata), token);
		} else if ("get".equals(method)) {
			// 获取标签
			resultJson = WeixinUtil.getTags(token);
		}
		
		// 创建标签
		/*JSONObject nameJson = new JSONObject();
		nameJson.put("name", "代购");
		json.put("tag", nameJson);
		result = WeixinUtil.createTags(json, token);*/
		
		// 编辑标签
		/*JSONObject editJson = new JSONObject();
		editJson.put("id", 100);
		editJson.put("name", "编辑");
		json.put("tag", editJson);
		result = WeixinUtil.updateTags(json, token);*/
		
		// 删除标签
		/*JSONObject idJson = new JSONObject();
		idJson.put("id", 103);
		json.put("tag", idJson);
		result = WeixinUtil.deleteTags(json, token);*/
		
		// 为用户打标签
		/*String[] openid_list = new String[] { "ogABSt4mgj8dBdGZZZiS95YlqHts" };
		json.put("tagid", 102);
		json.put("openid_list", openid_list);
		result = WeixinUtil.batchUserTags(json, token);*/
		
		// 获取标签用户
		/*json.put("tagid", 100);
		json.put("next_openid", "");
		json = WeixinUtil.getTagUsers(json, token);*/
//		logger.info("获取标签用户 json = " + json);
		
		resultJson.put(RESULT, result);
		
		return resultJson;
	}

	protected String getBasePath() {
		return null;
	}
}
